<!-- TopicSearch.vue -->
<template>
  <div class="search-container">
    <div class="search-wrapper">
      <el-input
        v-model="searchQuery"
        placeholder="搜索讨论..."
        class="search-input"
        :prefix-icon="Search"
        @input="handleSearchInput"
      >
      </el-input>

      <!-- 话题建议列表 -->
      <div v-if="showSuggestions && topicSuggestions.length > 0" class="suggestions">
        <div
          v-for="topic in topicSuggestions"
          :key="topic.topic"
          class="suggestion-item"
          @click="selectTopic(topic.topic)"
        >
          {{ topic.topic }}
        </div>
      </div>

      <!-- 无搜索结果提示 -->
      <div v-if="showSuggestions && topicSuggestions.length === 0 && searchQuery" class="no-suggestions">
        <el-empty
          description="未找到相关话题"
          :image-size="60"
        >
          <template #description>
            <p>未找到"{{ searchQuery }}"相关话题</p>
            <p class="sub-text">换个关键词试试吧</p>
          </template>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const emit = defineEmits(['update:posts'])

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})

const searchQuery = ref('')
const topicSuggestions = ref([])
const showSuggestions = ref(false)

// 处理搜索输入
const handleSearchInput = async () => {
  if (!searchQuery.value) {
    topicSuggestions.value = []
    showSuggestions.value = false
    return
  }

  try {
    const response = await axios.get('/backend/api/post/topics/search/', {
      params: {
        keyword: searchQuery.value
      },
      withCredentials: true
    })
    topicSuggestions.value = response.data
    showSuggestions.value = true
  } catch (error) {
    console.error('获取话题建议失败:', error)
    ElMessage.error('获取话题建议失败')
  }
}

// 选择话题
const selectTopic = (topic) => {
  searchQuery.value = topic
  showSuggestions.value = false
  handleSearch()
}

// 处理搜索
const handleSearch = async () => {
  if (!searchQuery.value) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    const response = await axios.get('/backend/api/post/search/', {
      params: {
        topic: searchQuery.value,
        course_id: props.courseId
      },
      withCredentials: true
    })

    if (response.data.length === 0) {
      ElMessage.info('未找到相关帖子')
    }

    emit('update:posts', response.data)
    showSuggestions.value = false
  } catch (error) {
    console.error('搜索帖子失败:', error)
    ElMessage.error('搜索帖子失败')
  }
}
</script>

<style scoped>
.search-container {
  margin-bottom: 24px;
  display: flex;
  justify-content: center;
  width: 100%;
}

.search-wrapper {
  position: relative;
  width: 500px;
}

.search-input {
  width: 100%;
}

.suggestions, .no-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  width: 93%;
  background: white;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  z-index: 1000;
}

.suggestions {
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}

.no-suggestions {
  padding: 16px;
}

.sub-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式支持 */
@media (max-width: 768px) {
  .search-wrapper {
    width: 90%;
  }
}
</style>